package net.lwf.email;

import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import net.lwf.exception.ExceptionUtil;

import org.apache.log4j.Logger;



public class EmailNotification {
	
	private static final Logger logger = Logger.getLogger(net.lwf.email.EmailNotification.class);
	
	public static void sendFeedbackMail(String userid, String bodycontent) {
		sendMyMail("Feedback from " + userid, bodycontent, "info@learnwithfun.net", "info@learnwithfun.net");
	}
	
	public static void sendError(String userid, String exceptionId) {
		String bodycontent = "Generated Exception Id: " + exceptionId + "; User Id: " + userid;
		sendMyMail("Runtime Exception Occurred at " + new Date().toString(), bodycontent, "info@learnwithfun.net", "info@learnwithfun.net");
	}
	
	
	public static void sendMail(String userid, String bodycontent, EmailProperties properties) {
		sendMail("Feedback from " + userid, bodycontent, properties.getSendersEmail(), "mycodetalks@gmail.com", properties);
	}
	
	private static  void sendMail(String subject, String body, String sender, String recipients, EmailProperties properties)	{	

		logger.debug("....... Sending Email - STEP 1................");
		logger.debug(properties.toString());
		
		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
		 
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", properties.getProtocol());
		props.setProperty("mail.host", properties.getHost());
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", properties.getPort());
		props.put("mail.smtp.socketFactory.port", properties.getPort());
		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.quitwait", "false");
 
		Session session = Session.getDefaultInstance(props,
				getAuthenticator(properties.getUserid(), properties.getPassword()));		
 
		MimeMessage message = new MimeMessage(session);
		try {
			message.setSender(new InternetAddress(sender));
			message.setSubject(subject);
			message.setContent(body, "text/plain");
			if (recipients.indexOf(',') > 0) {
				message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
			}
						
			else {
				message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
			}
			Transport.send(message);
		} catch (AddressException addrex) {
			ExceptionUtil.logAndThrowException(EmailNotification.class, addrex);
		} catch (MessagingException msgex) {
			ExceptionUtil.logAndThrowException(EmailNotification.class, msgex);
		}
		
	}


	private static Authenticator getAuthenticator(String userid, String password) {
		final String userId = userid;
		final String pwd = password;
		return new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(userId, pwd);
			}
		};
	}
	
	
	private static  void sendMyMail(String subject, String body, String sender, String recipients)	{	
		Properties props = new Properties();
		props.setProperty("mail.smtp.host", "localhost");
		Session session = Session.getInstance(props, null);		
		MimeMessage message = new MimeMessage(session);
		try {
			message.setFrom(new InternetAddress(sender));
			message.setSubject(subject);
			message.setContent(body, "text/plain");
			if (recipients.indexOf(',') > 0) {
				message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
			}
						
			else {
				message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
			}
			Transport.send(message);
		} catch (AddressException addrex) {
			ExceptionUtil.logAndThrowException(EmailNotification.class, addrex);
		} catch (MessagingException msgex) {
			ExceptionUtil.logAndThrowException(EmailNotification.class, msgex);
		}
		
	}
	
	private static EmailProperties getDefaults() {
		EmailProperties properties = new EmailProperties();
		properties.setHost("smtp.gmail.com");
		properties.setPort("465");
		properties.setProtocol("smtp");
		properties.setSendersEmail("mycodetalks@gmail.com");
		properties.setUserid("userid");
		properties.setPassword("password");
		return properties;
	}

}